import IgnoreError from "@/errors/IgnoreError";
import Reflect from "@/utils/reflect";
import { AnyAsyncFunc } from "./type";

export function Ensuring() {
  return function(target: any, propertyKey: string, descriptor: TypedPropertyDescriptor<AnyAsyncFunc>) {
    Reflect.setValue(target, ["Ensuring", propertyKey], descriptor.value);
    descriptor.value = async function(...args) {
      const startCount = Reflect.addValue(this, ["ensuringCount", propertyKey]);
      const result = await Reflect.getValue<AnyAsyncFunc>(target, ["Ensuring", propertyKey]).call(this, ...args);
      const endCount = Reflect.getValue(this, ["ensuringCount", propertyKey], 0);
      if (startCount !== endCount) {
        throw new IgnoreError();
      }
      return result;
    }
  }
}
